package com.xiaohudie.SGGJUC;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author xiao hu die
 * @Date 2022/3/6 23:14
 * @Version 1.0
 */
public class TestAnswer2 {
    public static void main(String[] args) {
        BigCar2 bigCar2 = new BigCar2();
        new Thread(() -> {
            for (int i = 0; i <10 ; i++) {
                bigCar2.SoutA();
            }},"AA").start();
        new Thread(() -> {
            for (int i = 0; i <10 ; i++) {
                bigCar2.SoutB();
        }},"BB").start();
        new Thread(() -> {
            for (int i = 0; i <10 ; i++) {
                bigCar2.SoutC();
            }},"CC").start();
    }
}
class BigCar2{
    private Lock lock =new ReentrantLock();
    private Condition condition1 =lock.newCondition();
    private Condition condition2 =lock.newCondition();
    private Condition condition3 =lock.newCondition();
    private Integer flag = 1;
    public void  SoutB(){
        lock.lock();
        try {
            while (flag !=2){
                try {
                    condition2.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println(Thread.currentThread().getName()+"--->");
            flag=3;
            condition3.signal();
        }finally {
            lock.unlock();
        }
    }
    public void  SoutC(){
        lock.lock();
        try {
            while (flag !=3){
                try {
                    condition3.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println(Thread.currentThread().getName()+"--->");
            flag=1;
            condition1.signal();
        }finally {
            lock.unlock();
        }
    }
    public void  SoutA(){
        lock.lock();
        try {
            while (flag !=1){
                try {
                    condition1.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println(Thread.currentThread().getName()+"--->");
            flag=2;
            condition2.signal();
        }finally {
            lock.unlock();
        }
    }

}
